﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using ServiceOfSansar.Models;

namespace ServiceOfSansar
{
    [ErrorHandler]

    public class UtmInterface
    {
        private SansarEntities db;
        TelnetConnection tc;
        bool isLoggedIn;
        public UtmInterface()
        {
            db = new SansarEntities();
            isLoggedIn = false;
            tc = new TelnetConnection(Properties.Settings.Default.UtmServer, 23);
            if (!tc.connectedOrNot) tc = null;
            //Console.WriteLine(tc.IsConnected.ToString());
            ConnectTelnet();
        }
        ~UtmInterface()
        {
            db.Dispose();
        }
        public Result addUser(string login, string password)
        {
            Result res = ExecuteTelnetCommand("/netup/utm5/bin/utm5_urfaclient -a add_user -login " + login + " -password " + password + " -balance 10");
            if (res.Code == 0)
            {
                if (res.Message.Contains("user_id"))
                    return new Result(0, "Successfull!");
                else if (res.Message.Contains("Exit code 10"))
                    return new Result(1, "Hereglegch nemj bh ued aldaa garlaa! Hereglegch davhardaj bna! " + res.Message);
                else
                    return new Result(1, "Hereglegch nemj bh ued aldaa garlaa! UTM interface error! " + res.Message);
            }
            else
            {
                return new Result(1, res.Message);
            }
        }
        public Int32 DateTimeToUnixTimestamp(DateTime? dateTime)
        {
            return Convert.ToInt32(((DateTime)dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds);
        }
        public UtmUser getUTMuser(string sql)
        {
            UtmUser retItem = new UtmUser { account_id=0, cust_id=0};
            foreach (UtmUser usr in db.ExecuteStoreQuery<UtmUser>(sql))
            {
                retItem = usr;
            }
            return (retItem);
        }
        public bool UserExists(string user)
        {
            UtmUser Utm_user = getUTMuser("SELECT basic_account account_id,[id] cust_id"
                + " FROM openquery(SI1,'SELECT *FROM users') WHERE [login]='" + user + "'");
            if (Utm_user.cust_id == 0)
            {
                return false;
            }
            return true;
        }
        public Result EditService(string NewLogin, string NewPass, string OldLogin, string OldPass)
        {
            // Get user account
            UtmUser Utm_user = getUTMuser("SELECT basic_account account_id,[id] cust_id"
            + " FROM openquery(SI1,'SELECT *FROM users') WHERE [login]='" + OldLogin + "'");
            if (Utm_user.cust_id == 0)
            {
                return new Result(1, OldLogin + " gesen hereglegch oldsongui!");
            }
            else
            {
                //Edit user
                ExecuteTelnetCommand("/netup/utm5/bin/utm5_urfaclient -a edit_user -user_id "
                + Utm_user.cust_id.ToString() + " -login " + NewLogin + " -password " + NewPass);
            }

            // Saving current service links data
            string sql = "SELECT *FROM openquery(SI1,'SELECT login,password,c.service_id," +
            "start_date,expire_date FROM dialup_service_links a " +
            "INNER JOIN periodic_service_links b ON a.id=b.id " +
            "AND a.is_deleted=0 AND b.is_deleted=0 INNER JOIN service_links c " +
            "ON a.id=c.id AND c.is_deleted=0 WHERE login=''" + OldLogin + "''')";
            UtmService retItem = new UtmService { service_id = -1 };
            foreach (UtmService utmsrv in db.ExecuteStoreQuery<UtmService>(sql))
            {
                retItem = utmsrv;
            }
            Result res=new Result() {Code=0,Message="Амжилттай заслаа!"};
           // if (retItem.service_id == -1) return new Result(1, OldLogin + " gesen login oldsongui!");

        // Delete old service links
            foreach (Int32 sid in db.ExecuteStoreQuery<Int32>("SELECT [id] FROM " +
            "openquery(SI1,'SELECT * FROM dialup_service_links')" +
            "WHERE login='" + OldLogin + "' AND is_deleted=0"))
            {
                res = ExecuteTelnetCommand(@"/netup/utm5/bin/utm5_urfaclient -a unlink_service -slink_id " + sid.ToString());
            }
            // Add service links
            if (retItem.service_id != -1)
            {
                string execCommand = @"/netup/utm5/bin/utm5_urfaclient "
                + "-a link_service -user_id " + Utm_user.cust_id.ToString() + " -account_id " + Utm_user.account_id.ToString()
                + " -service_id " + retItem.service_id.ToString()
                + " -discount_period_id 1 -start_date " + retItem.start_date.ToString()
                + " -expire_date " + retItem.expire_date.ToString()
                + " -dialup_login " + NewLogin + " -dialup_password " + NewPass;

                res = ExecuteTelnetCommand(execCommand);
            }
            if (res.Code == 0)
            {
                if (res.Message.Contains("rpcf_add_service_to_user"))
                    return new Result { Code = 0, Message = "Amjilttai burtgelee!" };
                else if (res.Message.Contains("ERROR:"))
                    return new Result(1, "Service nemj bh ued aldaa garlaa! UTM interface error! " + res.Message);
                else
                    return new Result(0, "Amjilttai burtgelee!" + res.Message);

            }
            else
            {
                return new Result(1, res.Message);
            }
        }

        public Result DeleteAllService(string login)
        {
            //UtmUser Utm_user = getUTMuser("SELECT basic_account account_id,[id] cust_id"
            //+ " FROM openquery(SI1,'SELECT *FROM users') WHERE [login]='" + login + "'");
            //if (Utm_user.cust_id == 0) return new Result(1, login + " gesen hereglegch oldsongui!");

            // Delete old service links
            Result res = new Result(0, "Successfull!");
            foreach (Int32 sid in db.ExecuteStoreQuery<Int32>("SELECT [id] FROM " +
            "openquery(SI1,'SELECT * FROM dialup_service_links')" +
            "WHERE login='" + login + "' AND is_deleted=0"))
            {
                res = ExecuteTelnetCommand(@"/netup/utm5/bin/utm5_urfaclient -a unlink_service -slink_id " + sid.ToString());
            }
            return res;
        }

        public Result addServce(string userid, string login, string password, Int32 prodcode, DateTime? startdate, DateTime? enddate)
        {
            UtmUser Utm_user = getUTMuser("SELECT basic_account account_id,[id] cust_id"
            + " FROM openquery(SI1,'SELECT *FROM users') WHERE [login]='" + userid + "'");
            if (Utm_user.cust_id == 0) return new Result(1, login + " gesen hereglegch oldsongui!");

            DateTime dt1 = startdate ?? DateTime.Now;
            DateTime dt2 = enddate ?? DateTime.Now;

            string startstamp = DateTimeToUnixTimestamp(DateTime.ParseExact(dt1.ToString("yyyy-MM-dd") + " 00:00:00", "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)).ToString();
            string endstamp = DateTimeToUnixTimestamp(DateTime.ParseExact(dt2.ToString("yyyy-MM-dd") + " 23:59:59", "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)).ToString();
            string service_id = ((new Register()).GetProduct(prodcode).UtmCode).ToString();
            // Delete old service links
            foreach (Int32 sid in db.ExecuteStoreQuery<Int32>("SELECT [id] FROM " +
            "openquery(SI1,'SELECT * FROM dialup_service_links')" +
            "WHERE login='" + login + "' AND is_deleted=0"))
            {
                Result rs = ExecuteTelnetCommand(@"/netup/utm5/bin/utm5_urfaclient -a unlink_service -slink_id " + sid.ToString());
            }
            // Add service links
            string execCommand = @"/netup/utm5/bin/utm5_urfaclient "
            + "-a link_service -user_id " + Utm_user.cust_id.ToString() + " -account_id " + Utm_user.account_id.ToString()
            + " -service_id " + service_id
            + " -discount_period_id 1 -start_date " + startstamp + " -expire_date " + endstamp
            + " -dialup_login " + login + " -dialup_password " + password;

            Result res = ExecuteTelnetCommand(execCommand);

            if (res.Code == 0)
            {
                if (res.Message.Contains("rpcf_add_service_to_user"))
                    return new Result(0, "Successfull!");
                else
                    return new Result(1, "Service nemj bh ued aldaa garlaa! UTM interface error! " + res.Message);
            }
            else
            {
                return new Result(1, res.Message);
            }
        }

        public Result AddTxnListToUtm(DateTime txndate)
        {
            // Delete old service links
            try
            {
                foreach (UtmTxnService txn in db.ExecuteStoreQuery<UtmTxnService>("  SELECT Jrno,MAX(b.UserName) username"
                + ",MAX(b.[Password]) pass,MAX(a.ProdCode) prod,MIN(a.StartDate) startdate,MAX(b.EndDate)"
                + " enddate FROM [Transaction] a INNER JOIN Contract b ON a.ContractNo=b.ContractNo "
                + " WHERE a.TxnType IN (1200,1201) AND CONVERT(CHAR(8),a.StartDate,112)='" + txndate.ToString("yyyyMMdd") + "' AND a.Status=1 GROUP BY Jrno ORDER BY JrNo"))
                {
                    Result rs = addServce(txn.username, txn.username, txn.pass, txn.prod, txn.startdate, txn.enddate);
                    db.UtmTxns.AddObject(new UtmTxn { JrNo = txn.jrno, TxnDate = txndate, UserName = txn.username, ProdCode = txn.prod, PostDate = DateTime.Now, StartDate = txn.startdate, EndDate = txn.enddate, UtmStatus = rs.Code, UtmDescription = rs.Message });
                }
                db.SaveChanges();
                return new Result(0, "UTM servce amjilttai uusgegdlee.");
            }
            catch (Exception e)
            {
                return new Result(1, "Service auto uusgej baih yavtsad aldaa garlaa! "+e.Message);
            }
            // Add service links
        }
        public bool ConnectTelnet()
        {
            //TelnetConnection tc = new TelnetConnection(Properties.Settings.Default.UtmServer, 23);
            if (tc == null) return false;
            string s = tc.Login(Properties.Settings.Default.UtmUser, Properties.Settings.Default.UtmPass, 200);
            Console.WriteLine(s);
            
            string prompt = s.TrimEnd();
            prompt = s.Substring(prompt.Length - 1, 1);
            if (prompt != "$" && prompt != ">")
            {
                isLoggedIn = false;
                return false;
            }
            isLoggedIn = true;
            return true;
        }
        public Result ExecuteTelnetCommand(string command)
        {
            if (tc == null) return new Result() { Code = 1, Message = "UTM servertei holbogdoj chadsangui!" };
            if (!tc.IsConnected || isLoggedIn==false)
            {
                if (!ConnectTelnet()) return new Result() { Code = 1, Message = "UTM servertei holbogdoj chadsangui!" };
            }
            
                //Console.Write(tc.Read());
                tc.WriteLine(command);
                Console.WriteLine(command + ":::");
                string response = tc.Read();
                response = response+"_____"+tc.Read();
                Console.WriteLine(response);
                return new Result() { Code = 0, Message = response };
            
            //return new Result() { Code = 1, Message = "UTM servertei holbogdoj chadsangui!" };
        }
    }
}
